*********************************************************************************
* Table 6. Beliefs – Baseline OLS, OLS+IPW for selection, IPWRA (analytic SEs)
*********************************************************************************
clear
set more off
global dir "replication"

        if "$dir"=="ana"  {  
        global root   = "/Users/adiazescobar/Library/CloudStorage/Dropbox/GenderNorms2/Results/"
        global output = "/Users/adiazescobar/Library/CloudStorage/Dropbox/GenderNorms2/Results/"
        }   
        if "$dir"=="ana_imac"  {  
        global root   = "/Users/adaizescobar/Dropbox/GenderNorms2/Results"
        global output = "/Users/adaizescobar/Dropbox/GenderNorms2/Results"
        }   

if "$dir"=="marie"  {
    global root   = "C:\Users\Marie Boltz\Dropbox\Gender Norms2\Results\"
    global output = "C:\Users\Marie Boltz\Dropbox\Gender Norms2\Results\"
}

if "$dir"=="replication" {
    global root   = "."
    global output = "."
    global datadir = "./data"
    global codedir = "./code"
    global outdir  = "./output"
    capture mkdir "$outdir"
}

*cd "C:/Users/Marie Boltz/Dropbox/Gender Norms2/Results/Analysis/FINAL/Tables"
* ---- QJE-style graph defaults ----
set scheme s2mono
graph set window fontface "Times New Roman"
global GCOMMON graphregion(color(white)) ///
    plotregion(margin(l+8 r+8 t+8 b+8)) ///
    xlabel(, angle(0) labsize(small)) ///
    ylabel(, labsize(small)) ///
    title(, size(small)) subtitle(, size(vsmall)) ///
    note("", size(vsmall))
global GCOMB graphregion(color(white)) imargin(tiny)

****************************************
use "$datadir/dataALLWAVES.dta", clear

run "$codedir/def_samples.do"


global reps 1000

drop if female_w3 != female & female_w3!=.


capture mkdir "C:/temp_ols"
cd "C:/temp_ols"

*********************************************************************************
* Table 8. Changes in interest about wife's LFP – IPWRA (analytic SEs, main text) + OLS (appendix)
*********************************************************************************


**# Definitions

* Main sample indicator::
local samples sample1 /*sample1_any sample1_alone sample1_other sample1_both*/

* Baseline belief block (used in diagnostics)
local bel2  fob2 sob2 sob2m sob2p

* "Strata" covariates used in absorb() and IPW models
local strat inactiveF employedF fob2M

* Outcomes: comment/uncomment to include/exclude
local yvars y1 y2 y3 /*y4 y5*/


* Initial control variables (diagnostics)
local xvars c1 c2_2_rp c3 c5 f6 age_dif  level_1 level_2 edu_WmoreH  inactiveM unemployedM estrato_12 estrato_3 tec_2 

local reps $reps


   /********************************************************************
     * 1. BASELINE OLS (no selection weights): pooled model only
     *    Male/Female enter as stats rows
     ********************************************************************/


		foreach sample in `samples' {






********************************************************************************
* STORAGE MACROS FOR THE THREE TABLES
********************************************************************************
eststo clear
local j = 1


********************************************************************************
* LOOP OVER OUTCOMES
********************************************************************************



foreach y of local yvars {
	
    * (1) Pooled OLS, no interaction, control for female
    reghdfe `y' D female DFem `vars_sample3'  ///
        if `sample' == 1, absorb(`strat') vce(cluster id)
   scalar N_all = e(N)
    eststo OLS_base_A`j'

    *** Means of Y by subgroup (unweighted)
    quietly summarize `y' if `sample' == 1
    scalar ymean_all  = r(mean)

    quietly summarize `y' if `sample' == 1 & female == 0
    scalar ymean_male = r(mean)

    quietly summarize `y' if `sample' == 1 & female == 1
    scalar ymean_fem  = r(mean)
	
	* Attach means to the "all" model (we'll reuse them in stats)
	estimates restore OLS_base_A`j'
	estadd scalar ymean_all  = ymean_all,  replace
	estadd scalar ymean_male = ymean_male, replace
	estadd scalar ymean_fem  = ymean_fem,  replace
	eststo OLS_base_A`j'

    * (2) OLS – males only
    reghdfe `y' D `vars_sample3' ///
        if `sample' == 1 & female == 0, ///
        absorb(`strat') vce(cluster id)
		
	eststo OLS_base_M`j'	
    
	* (3) OLS – females only
    reghdfe `y' D `vars_sample3' ///
        if `sample' == 1 & female == 1, ///
        absorb(`strat') vce(cluster id)
    
	eststo OLS_base_F`j'

    ********************************************************************
    * RITEST p-values for OLS coefficients on D
    ********************************************************************
    * (4) RI – pooled, coefficient on D
	* Pooled (D, female, Dfem) – RI p-val for D, female, Dfem
	scalar p_ri_D_all    = .
	scalar p_ri_fem_all  = .
	scalar p_ri_Dfem_all = .

	capture noisily ritest D female DFem///
		(_b[D]) (_b[female]) (_b[DFem]), ///
		cluster(id) strata(`strat') reps(`reps') : ///
		reghdfe `y' D female DFem `vars_sample3' ///
		if `sample' == 1, absorb(`strat') vce(cluster id)

	if (_rc == 0) {
		matrix P = r(p)
		scalar p_ri_D_all    = round(P[1,1], .001)
		scalar p_ri_fem_all  = round(P[1,2], .001)
		scalar p_ri_Dfem_all = round(P[1,3], .001)
	}

	estimates restore OLS_base_A`j'
	estadd scalar p_ri_D_all    = p_ri_D_all,    replace
	estadd scalar p_ri_fem_all  = p_ri_fem_all,  replace
	estadd scalar p_ri_Dfem_all = p_ri_Dfem_all, replace
	eststo OLS_base_A`j'


    * (5) RI – males only
   scalar p_ri_D_male = .
	capture noisily ritest D _b[D], ///
		cluster(id) strata(`strat') reps(`reps') : ///
		reghdfe `y' D `vars_sample3' ///
		if `sample' == 1 & female == 0, ///
		absorb(`strat') vce(cluster id)
	if (_rc == 0) {
		matrix Pm = r(p)
		scalar p_ri_D_male = round(Pm[1,1], .001)
	}
	estimates restore OLS_base_M`j'
	estadd scalar p_ri_D_male = p_ri_D_male, replace
	eststo OLS_base_M`j'

    * (6) RI – females only
	scalar p_ri_D_female = .
	capture noisily ritest D _b[D], ///
		cluster(id) strata(`strat') reps(`reps') : ///
		reghdfe `y' D `vars_sample3' ///
		if `sample' == 1 & female == 1, ///
		absorb(`strat') vce(cluster id)
	if (_rc == 0) {
		matrix Pf = r(p)
		scalar p_ri_D_female = round(Pf[1,1], .001)
	}
	estimates restore OLS_base_F`j'
	estadd scalar p_ri_D_female = p_ri_D_female, replace
	eststo OLS_base_F`j'
	
  local j = `j' + 1
 
}

*=====================================================
* Table 8A – BASELINE OLS (no selection weights)
*=====================================================

est dir

local cells_3lines ///
    "b(star fmt(%9.3f)) se(par) p(par([ ]))"

local mtitles_ols_base  "(1)" "(2)" "(3)"

local outfile "$root\Analysis\FINAL\Tables\T8_Course_OLS_base_DxFem_`sample'.tex"
display "`outfile'"

* Panel A - All respondents 

capture mkdir "C:/temp_ols"
cd "C:/temp_ols"
	


*=============== Panel A: All respondents ===============*
* PANEL A – All respondents
esttab OLS_base_A1 OLS_base_A2 OLS_base_A3 ///
    using "T8_Course_OLS_base_All.tex", ///
    replace booktabs ///
    cells(b(fmt(%9.3f)) se(par) p(par([ ]))) ///
    title(Changes in interest about wife's LFP -- Baseline OLS \label{tab8}) ///
    prehead(`"\begin{table}[H]\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}"' ///
            `"\centering"' ///
            `"\begin{threeparttable}"' ///
            `"\footnotesize"' ///
            `"\caption{@title}"' ///
            `"\begin{tabular}{lccc}"' ///
            `"\toprule \addlinespace"' ///
            `"{\bf Dependent Variable} & \begin{tabular}[c]{@{}c@{}}Wife Should\\Attend Course\end{tabular} & \begin{tabular}[c]{@{}c@{}}Self:\\Interested\end{tabular} & \begin{tabular}[c]{@{}c@{}}Partner:\\Believed\\Interested\end{tabular} \\[0.5ex]"' ///
            `"\midrule \addlinespace"') ///
    posthead( `"\multicolumn{4}{l}{\bf Panel A: All respondents} \\[0.5ex]"') ///
    varlabels(D "Treatment" female "Women" DFem "Treatment $\times$ Women", end("") nolast) ///
    keep(D female DFem) ///
    stats(N ymean_all p_ri_D_all p_ri_fem_all p_ri_Dfem_all, ///
          fmt(%9.0f %9.3f %9.3f %9.3f %9.3f) ///
          labels("N" ///
                 "Mean Dep. Var (All)" ///
                 "{Fisher p-val D}" ///
                 "{Fisher p-val Female}" ///
                 "{Fisher p-val D×Female}")) ///
    collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none) ///
    prefoot(`"\cdashline{1-4} \addlinespace"') ///
    postfoot( `"\bottomrule"'`"\end{tabular}"' ///
			`"\begin{tablenotes}[flushleft]\footnotesize"' ///
             `"\item \textit{Notes}: Coefficients with clustered standard errors in parentheses ( ). Clustered \$p\$-values in brackets [ ]. Fisher randomization $p$-values in braces \{ \}."' ///
             `"\end{tablenotes}"' ///
             `"\end{threeparttable}"' ///
             `"\end{table}"')



* PANEL B – Men only
esttab OLS_base_M1 OLS_base_M2 OLS_base_M3 ///
    using "T8_Course_OLS_base_Men.tex", ///
    replace booktabs ///
    cells(b(fmt(%9.3f)) se(par) p(par([ ]))) ///
    title(Changes in interest about wife's LFP -- Men only) ///
    prehead(`"\begin{table}[H]"' ///
            `"\centering"' ///
            `"\footnotesize"' ///
            `"\begin{threeparttable}"' ///
            `"\caption{@title}"' ///
            `"\begin{tabular}{lccc}"' ///
            `"\toprule \addlinespace"' ///
            `"{\bf Dependent Variable} & \begin{tabular}[c]{@{}c@{}}Wife Should\\Attend Course\end{tabular} & \begin{tabular}[c]{@{}c@{}}Self:\\Interested\end{tabular} & \begin{tabular}[c]{@{}c@{}}Partner:\\Believed\\Interested\end{tabular} \\[0.5ex]"' ///
            `"\midrule \addlinespace"') ///
    posthead(`"\multicolumn{4}{l}{\bf Panel B: Men only} \\[0.5ex]"') ///
    keep(D) ///
    stats(N p_ri_D_male, ///
          fmt(%9.0f %9.3f) ///
          labels("N (Men)" "{Fisher p-val D (Men)}")) ///
    collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none) ///
    prefoot(`"\hdashline\addlinespace"' ) ///
    postfoot(`"\bottomrule"'`"\end{tabular}"' `"\begin{tablenotes}[flushleft]\footnotesize"' ///
             `"\item \textit{Notes}: Men-only subsample. Same controls as baseline specification."' ///
             `"\end{tablenotes}"' ///
             `"\end{threeparttable}"' ///
             `"\end{table}"')

* PANEL C – Women only
esttab OLS_base_F1 OLS_base_F2 OLS_base_F3 ///
    using "T8_Course_OLS_base_Women.tex", ///
    replace booktabs ///
    cells(b(fmt(%9.3f)) se(par) p(par([ ]))) ///
    title(Changes in interest about wife's LFP -- Women only) ///
    prehead(`"\begin{table}[H]"' ///
            `"\centering"' ///
            `"\footnotesize"' ///
            `"\begin{threeparttable}"' ///
            `"\caption{@title}"' ///
            `"\begin{tabular}{lccc}"' ///
            `"\toprule \addlinespace"' ///
            `"{\bf Dependent Variable} & \begin{tabular}[c]{@{}c@{}}Wife Should\\Attend Course\end{tabular} & \begin{tabular}[c]{@{}c@{}}Self:\\Interested\end{tabular} & \begin{tabular}[c]{@{}c@{}}Partner:\\Believed\\Interested\end{tabular} \\[0.5ex]"' ///
            `"\midrule \addlinespace"') ///
    posthead(`"\multicolumn{4}{l}{\bf Panel C: Women only} \\[0.5ex]"') ///
    keep(D) ///
    stats(N p_ri_D_female, ///
          fmt(%9.0f %9.3f) ///
          labels("N (Women)" "{Fisher p-val D (Women)}")) ///
    collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none) ///
    prefoot(`"\hdashline \addlinespace"' ) ///
    postfoot(`"\bottomrule"' `"\end{tabular}"'`"\begin{tablenotes}[flushleft]\footnotesize"' ///
             `"\item \textit{Notes}: Women-only subsample. Same controls as baseline specification."' ///
             `"\end{tablenotes}"' ///
             `"\end{threeparttable}"' ///
             `"\end{table}"')

		}
		
***************************************		

    /********************************************************************
     * 2. OLS WITH SELECTION IPW WEIGHTS: pooled model only
     ********************************************************************/



local samples sample1 /*sample1_any sample1_alone sample1_other sample1_both*/

* Baseline belief block (used in diagnostics)
local bel2  fob2 sob2 sob2m sob2p

* "Strata" covariates used in absorb() and IPW models
local strat inactiveF employedF fob2M

* Outcomes: comment/uncomment to include/exclude
local yvars y1 y2 y3 /*y4 y5*/


* Initial control variables (diagnostics)
local xvars c1 c2_2_rp c3 c5 f6 age_dif  level_1 level_2 edu_WmoreH  inactiveM unemployedM estrato_12 estrato_3 tec_2 

foreach sample in `samples' {
	
	********************************************************
* Diagnostics for attrition (who is in sample3_ext)
********************************************************

di "***************************************"
di "`sample'"
ta D female if `sample' ==1,m

* Diagnostics for attrition (who is in sample1_ext): only significant c5 level_1 tec_2 (barely sob2p)
reghdfe `sample' D `xvars' `bel2', absorb(`strat') vce(cluster id)
	* sample1 : female, c5, age, agedif, , tec_2, sob2m
	* sample1_any: female, c1, c5, f6, age_dif, level_2, inactiveM, tec_2, 
	* sample1_alone: female, c1, tec_2,sob2m (-)
	* sample1_other: female, c1, level_1, tec_2 
	* sample1_both: c3, c5, f6, level_1, edu_WmoreH, tec_2,
	
* Diagnostics for selective exposure (who takes D): only significant tec_2
reghdfe D `xvars' `bel2' if `sample' == 1, absorb(`strat') vce(cluster id)
	*sample1 : unemployedM, tec_2, sob2p
	*sample1_any: estrato12 (-), tec_2 (-), sob2p (-)
	*sample1_alone: estrato12 (-), estrato_3 (-), tec_2 (-), sob2m (+)
	*sample1_other: estrato12 (-), estrato_3 (-), tech_2 (-),
	*sample1_both: level_1, unemployedM, 
	
* logit : P(second répond) = f(sexe du premier) 
logit second_responds i.first_finisher##D edu_WmoreH  inactiveM unemployedM estrato_12 estrato_3 tec_2  c1 c2_2_rp c3 c5 f6 age_dif if tag_couple & n_spouses_chat >= 1
	

di "***************************************"
		
		

********************************************************************************
* IPW weights for selection (attrition weights for being in `sample')
********************************************************************************
cap drop ps_attrition 
cap drop w_*
cap drop wa_*
cap drop ws_*

	probit `sample' D `xvars' `bels' `strat', vce(cluster id)
	*probit `sample' D `xvars' `bels' `strat', vce(cluster id)

predict ps_attrition, pr 

gen w_`sample' = 1 / ps_attrition
quietly summ w_`sample'
local p_uncond = r(mean)
gen ws_`sample' = `p_uncond' / ps_attrition   // normalized (if needed)
gen wa_`sample' = 1                           // unweighted

* Default selection weight (you can switch to ws_ if you prefer normalized)
local weight w_`sample'
summ `weight' 
bys D : su `weight' if sample1 ==1
bys D : su `weight' ws_`sample' ps_attrition if sample1 ==1
local reps $reps

	
*local vars_sample3 female c5 f6 age_dif  unemployedM tec_2 sob2p	 sob2m	
local vars_sample3 `xvars' `bel2'
	
local j = 1
foreach y of local yvars {

    * (1) Pooled weighted OLS – All
    reghdfe `y' D female DFem `vars_sample3' ///
        if `sample' == 1 [pweight = `weight'], ///
        absorb(`strat') vce(cluster id)
    scalar N_all_w = e(N)
    eststo OLS_ipw_A`j'

    * Weighted means of Y by subgroup
    quietly summarize `y' [aweight = `weight'] if `sample' == 1
    scalar ymean_all_w = r(mean)

    quietly summarize `y' [aweight = `weight'] if `sample' == 1 & female == 0
    scalar ymean_male_w = r(mean)

    quietly summarize `y' [aweight = `weight'] if `sample' == 1 & female == 1
    scalar ymean_fem_w = r(mean)

    * Attach means to pooled weighted model
    estimates restore OLS_ipw_A`j'
    estadd scalar ymean_all_w  = ymean_all_w,  replace
    estadd scalar ymean_male_w = ymean_male_w, replace
    estadd scalar ymean_fem_w  = ymean_fem_w,  replace
    estadd scalar N_all_w      = N_all_w,      replace
    eststo OLS_ipw_A`j'

    * (2) Weighted OLS – Men only
    reghdfe `y' D `vars_sample3' ///
        if `sample' == 1 & female == 0 [pweight = `weight'], ///
        absorb(`strat') vce(cluster id)
    scalar N_male_w    = e(N)
    scalar b_D_male_w  = _b[D]
    scalar se_D_male_w = _se[D]
    scalar t_D_male_w  = b_D_male_w / se_D_male_w
    scalar p_D_male_w  = 2*(1 - normal(abs(t_D_male_w)))
    eststo OLS_ipw_M`j'

    * Attach male stats to male model
    estimates restore OLS_ipw_M`j'
    estadd scalar N_male_w   = N_male_w,   replace
    estadd scalar b_D_male_w = b_D_male_w, replace
    estadd scalar se_D_male_w = se_D_male_w, replace
    estadd scalar p_D_male_w = p_D_male_w, replace
    eststo OLS_ipw_M`j'

    * (3) Weighted OLS – Women only
    reghdfe `y' D `vars_sample3' ///
        if `sample' == 1 & female == 1 [pweight = `weight'], ///
        absorb(`strat') vce(cluster id)
    scalar N_fem_w    = e(N)
    scalar b_D_fem_w  = _b[D]
    scalar se_D_fem_w = _se[D]
    scalar t_D_fem_w  = b_D_fem_w / se_D_fem_w
    scalar p_D_fem_w  = 2*(1 - normal(abs(t_D_fem_w)))
    eststo OLS_ipw_F`j'

    * Attach female stats
    estimates restore OLS_ipw_F`j'
    estadd scalar N_fem_w    = N_fem_w,    replace
    estadd scalar b_D_fem_w  = b_D_fem_w,  replace
    estadd scalar se_D_fem_w = se_D_fem_w, replace
    estadd scalar p_D_fem_w  = p_D_fem_w,  replace
    eststo OLS_ipw_F`j'

    local j = `j' + 1
}

*=====================================================
* TABLE: OLS with selection IPW weights – All / Men / Women
*=====================================================



* PANEL A – All respondents, weighted
esttab OLS_ipw_A1 OLS_ipw_A2 OLS_ipw_A3 ///
    using "T8_Course_OLS_IPW_All.tex", ///
    replace booktabs ///
    cells(b(fmt(%9.3f)) se(par) p(par([ ]))) ///
    title(Changes in interest about wife's LFP -- OLS with IPW weights \label{tab8_ipw}) ///
    prehead(`"\begin{table}[H]\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}"' ///
            `"\centering"' ///
            `"\begin{threeparttable}"' ///
            `"\footnotesize"' ///
            `"\caption{@title}"' ///
            `"\begin{tabular}{lccc}"' ///
            `"\toprule \addlinespace"' ///
            `"{\bf Dependent Variable} & \begin{tabular}[c]{@{}c@{}}Wife Should\\Attend Course\end{tabular} & \begin{tabular}[c]{@{}c@{}}Self:\\Interested\end{tabular} & \begin{tabular}[c]{@{}c@{}}Partner:\\Believed\\Interested\end{tabular} \\[0.5ex]"' ///
            `"& \textbf{(1)} & \textbf{(2)} & \textbf{(3)} \\[0.5ex]"' ///
            `"\midrule \addlinespace"') ///
    posthead( `"\multicolumn{4}{l}{\bf Panel A: All respondents (IPW-weighted)} \\[0.5ex]"') ///
    varlabels(D "Treatment" female "Women" DFem "Treatment $\times$ Women", end("") nolast) ///
    keep(D female DFem) ///
    stats(N_all_w ymean_all_w, ///
          fmt(%9.0f %9.3f) ///
          labels("N (All, weighted)" ///
                 "Mean Dep. Var (All, weighted)")) ///
    collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none) ///
    prefoot(`"\cdashline{1-4} \addlinespace"') ///
    postfoot( `"\bottomrule"' `"\end{tabular}"' ///
              `"\begin{tablenotes}[flushleft]\footnotesize"' ///
              `"\item \textit{Notes}: Regressions weighted by inverse probability of being in the WhatsApp sample (selection IPW). Coefficients with clustered standard errors in parentheses ( ). Clustered \$p\$-values in brackets [ ]."' ///
              `"\end{tablenotes}"' ///
              `"\end{threeparttable}"' ///
              `"\end{table}"')

* PANEL B – Men only, weighted
esttab OLS_ipw_M1 OLS_ipw_M2 OLS_ipw_M3 ///
    using "T8_Course_OLS_IPW_Men.tex", ///
    replace booktabs ///
    cells(b(fmt(%9.3f)) se(par) p(par([ ]))) ///
    title(Changes in interest about wife's LFP -- Men only, OLS with IPW weights) ///
    prehead(`"\begin{table}[H]"' ///
            `"\centering"' ///
            `"\footnotesize"' ///
            `"\begin{threeparttable}"' ///
            `"\caption{@title}"' ///
            `"\begin{tabular}{lccc}"' ///
            `"\toprule \addlinespace"' ///
            `"{\bf Dependent Variable} & \begin{tabular}[c]{@{}c@{}}Wife Should\\Attend Course\end{tabular} & \begin{tabular}[c]{@{}c@{}}Self:\\Interested\end{tabular} & \begin{tabular}[c]{@{}c@{}}Partner:\\Believed\\Interested\end{tabular} \\[0.5ex]"' ///
            `"& \textbf{(1)} & \textbf{(2)} & \textbf{(3)} \\[0.5ex]"' ///
            `"\midrule \addlinespace"') ///
    posthead(`"\multicolumn{4}{l}{\bf Panel B: Men only (IPW-weighted)} \\[0.5ex]"') ///
    keep(D) ///
    stats(N_male_w p_D_male_w, ///
          fmt(%9.0f %9.3f) ///
          labels("N (Men, weighted)" "{Clustered p-val D (Men)}")) ///
    collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none) ///
    prefoot(`"\hdashline\addlinespace"' ) ///
    postfoot(`"\bottomrule"' `"\end{tabular}"' ///
             `"\begin{tablenotes}[flushleft]\footnotesize"' ///
             `"\item \textit{Notes}: Men-only subsample. Same controls and selection weights as in Panel A.}"' ///
             `"\end{tablenotes}"' ///
             `"\end{threeparttable}"' ///
             `"\end{table}"')

* PANEL C – Women only, weighted
esttab OLS_ipw_F1 OLS_ipw_F2 OLS_ipw_F3 ///
    using "T8_Course_OLS_IPW_Women.tex", ///
    replace booktabs ///
    cells(b(fmt(%9.3f)) se(par) p(par([ ]))) ///
    title(Changes in interest about wife's LFP -- Women only, OLS with IPW weights) ///
    prehead(`"\begin{table}[H]"' ///
            `"\centering"' ///
            `"\footnotesize"' ///
            `"\begin{threeparttable}"' ///
            `"\caption{@title}"' ///
            `"\begin{tabular}{lccc}"' ///
            `"\toprule \addlinespace"' ///
            `"{\bf Dependent Variable} & \begin{tabular}[c]{@{}c@{}}Wife Should\\Attend Course\end{tabular} & \begin{tabular}[c]{@{}c@{}}Self:\\Interested\end{tabular} & \begin{tabular}[c]{@{}c@{}}Partner:\\Believed\\Interested\end{tabular} \\[0.5ex]"' ///
            `"& \textbf{(1)} & \textbf{(2)} & \textbf{(3)} \\[0.5ex]"' ///
            `"\midrule \addlinespace"') ///
    posthead(`"\multicolumn{4}{l}{\bf Panel C: Women only (IPW-weighted)} \\[0.5ex]"') ///
    keep(D) ///
    stats(N_fem_w p_D_fem_w, ///
          fmt(%9.0f %9.3f) ///
          labels("N (Women, weighted)" "{Clustered p-val D (Women)}")) ///
    collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none) ///
    prefoot(`"\hdashline \addlinespace"' ) ///
    postfoot(`"\bottomrule"' `"\end{tabular}"' ///
             `"\begin{tablenotes}[flushleft]\footnotesize"' ///
             `"\item \textit{Notes}: Women-only subsample. Same controls and selection weights as in Panel A.}"' ///
             `"\end{tablenotes}"' ///
             `"\end{threeparttable}"' ///
             `"\end{table}"')
	

	
	
	*----------------------------------------------------
* 3. IPWRA – ATT/PO for All, Men, Women (analytic SEs)
*   → on crée une estimation IPWRA_`j' par outcome
*----------------------------------------------------

local j = 1

foreach y of local yvars {

    di "IPWRA for outcome: `y' (j=`j')"

    *---------------------------
    * (3.1) IPWRA – All
    *---------------------------
    teffects ipwra (`y' `strat') ///
                   (D `vars_sample3' `strat') ///
                   if `sample' == 1 [pweight=`weight'], ///
                   atet vce(cluster id)

    matrix bA = e(b)
    matrix VA = e(V)

    scalar ATET_all    = bA[1,1]
    scalar ATET_se_all = sqrt(VA[1,1])
    scalar ATET_pv_all = 2*(1 - normal(abs(ATET_all/ATET_se_all)))

    scalar PO_all      = bA[1,2]
    scalar PO_se_all   = sqrt(VA[2,2])
    scalar PO_pv_all   = 2*(1 - normal(abs(PO_all/PO_se_all)))

    *---------------------------
    * (3.2) IPWRA – Men only
    *---------------------------
    teffects ipwra (`y' `strat') ///
                   (D `vars_sample3' `strat') ///
                   if `sample' == 1 & female == 0 [pweight=`weight'], ///
                   atet vce(cluster id)

    matrix bM = e(b)
    matrix VM = e(V)

    scalar ATET_male    = bM[1,1]
    scalar ATET_se_male = sqrt(VM[1,1])
    scalar ATET_pv_male = 2*(1 - normal(abs(ATET_male/ATET_se_male)))

    scalar PO_male      = bM[1,2]
    scalar PO_se_male   = sqrt(VM[2,2])
    scalar PO_pv_male   = 2*(1 - normal(abs(PO_male/PO_se_male)))

    *---------------------------
    * (3.3) IPWRA – Women only
    *---------------------------
    teffects ipwra (`y' `strat') ///
                   (D `vars_sample3' `strat') ///
                   if `sample' == 1 & female == 1 [pweight=`weight'], ///
                   atet vce(cluster id)

    matrix bF = e(b)
    matrix VF = e(V)

    scalar ATET_fem    = bF[1,1]
    scalar ATET_se_fem = sqrt(VF[1,1])
    scalar ATET_pv_fem = 2*(1 - normal(abs(ATET_fem/ATET_se_fem)))

    scalar PO_fem      = bF[1,2]
    scalar PO_se_fem   = sqrt(VF[2,2])
    scalar PO_pv_fem   = 2*(1 - normal(abs(PO_fem/PO_se_fem)))

    *---------------------------
    * 3.4 – Créer un "container" IPWRA_`j'
    *       On part du modèle OLS_ipw_A`j' pour avoir une base
    *---------------------------
    estimates restore OLS_ipw_A`j'
    eststo IPWRA_`j'

    estimates restore IPWRA_`j'
    estadd scalar ATET_all    = ATET_all,    replace
    estadd scalar ATET_se_all = ATET_se_all, replace
    estadd scalar ATET_pv_all = ATET_pv_all, replace

    estadd scalar PO_all      = PO_all,      replace
    estadd scalar PO_se_all   = PO_se_all,   replace
    estadd scalar PO_pv_all   = PO_pv_all,   replace

    estadd scalar ATET_male     = ATET_male,     replace
    estadd scalar ATET_se_male  = ATET_se_male,  replace
    estadd scalar ATET_pv_male  = ATET_pv_male,  replace

    estadd scalar PO_male       = PO_male,       replace
    estadd scalar PO_se_male    = PO_se_male,    replace
    estadd scalar PO_pv_male    = PO_pv_male,    replace

    estadd scalar ATET_fem      = ATET_fem,      replace
    estadd scalar ATET_se_fem   = ATET_se_fem,   replace
    estadd scalar ATET_pv_fem   = ATET_pv_fem,   replace

    estadd scalar PO_fem        = PO_fem,        replace
    estadd scalar PO_se_fem     = PO_se_fem,     replace
    estadd scalar PO_pv_fem     = PO_pv_fem,     replace

    eststo IPWRA_`j'

    * pour les titres de colonnes : label de la variable si existe
    local ylab : variable label `y'
    if "`ylab'" == "" local ylab "`y'"
    local mtitles_ipwra `"`mtitles_ipwra' "`ylab'""'

    local j = `j' + 1
}

	
	*=====================================================
* Export table IPWRA – All / Men / Women
*=====================================================

* On reste simple pour le chemin, tu peux changer après


#delimit ;
local opts_ipwra style(tex)
  cells(none) /* pas de coefficients, seulement stats() */
  stats(ATET_all ATET_se_all ATET_pv_all
        PO_all   PO_se_all   PO_pv_all
        ATET_male ATET_se_male ATET_pv_male
        PO_male   PO_se_male   PO_pv_male
        ATET_fem  ATET_se_fem  ATET_pv_fem
        PO_fem    PO_se_fem    PO_pv_fem,
        fmt(%9.3f)
        label("ATT All"
              "Std. Err. ATT All"
              "P-value ATT All"
              "PO All"
              "Std. Err. PO All"
              "P-value PO All"
              "ATT Men"
              "Std. Err. ATT Men"
              "P-value ATT Men"
              "PO Men"
              "Std. Err. PO Men"
              "P-value PO Men"
              "ATT Women"
              "Std. Err. ATT Women"
              "P-value ATT Women"
              "PO Women"
              "Std. Err. PO Women"
              "P-value PO Women"))
  label collabels(none) msign(--) nolz varwidth(18) modelwidth(18)
  starlevels(* 0.10 ** 0.05 *** 0.01)
;
#delimit cr

estout IPWRA_1 IPWRA_2 IPWRA_3 using "Table_IPWRA_AllMenWomen_`sample'.tex", ///
    replace `opts_ipwra' mlabels(`mtitles_ipwra')

}
	
***************************************************************

	
	
		/*
	* TRIALS WITH APPEND 		 
			 

#delimit ;
esttab OLS_base_A1 OLS_base_A2 OLS_base_A3
    using "T8_Course_OLS_base_DxFem_`sample'.tex",
    replace booktabs
    cells(b(fmt(%9.3f)) se(par) p(par([ ])))
    title(Changes in interest about wife's LFP -- Baseline OLS \label{tab8})
    prehead(`"\begin{table}[H]\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}"'
            `"\centering"'
            `"\begin{threeparttable}"'
            `"\footnotesize"'
            `"\caption{@title}"'
            `"\begin{tabular}{lccc}"'
            `"\toprule \addlinespace"'
            `"{\bf Dependent Variable} & \begin{tabular}[c]{@{}c@{}}Wife Should\\Attend Course\end{tabular} & \begin{tabular}[c]{@{}c@{}}Self:\\Interested\end{tabular} & \begin{tabular}[c]{@{}c@{}}Partner:\\Believed\\Interested\end{tabular} \\[0.5ex]"'
            `"\midrule \addlinespace"')
    posthead(`"\multicolumn{4}{l}{\bf Panel A: All respondents} \\[0.5ex]"')
	prefoot(`"\addlinespace   \hdashline \addlinespace"') postfoot(`""')
    varlabels(D "Treatment" female "Women" DFem "Treatment $\times$ Women", end("") nolast)
    keep(D female DFem)
    stats(N ymean_all p_ri_D_all p_ri_fem_all p_ri_Dfem_all,
          fmt(%9.0f %9.3f %9.3f %9.3f %9.3f)
          labels("N"
                 "Mean Dep. Var (All)"
                 "{Fisher p-val D}"
                 "{Fisher p-val Female}"
                 "{Fisher p-val D×Female}"))
    collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none)
    ;
 
*=============== Panel B: Men only ===============*
esttab OLS_base_A1 OLS_base_A2 OLS_base_A3
    using "T8_Course_OLS_base_DxFem_`sample'.tex", append ;
	
	#delimit cr
		}

		/*
esttab OLS_base_M1 OLS_base_M2 OLS_base_M3 
	using "T8_Course_OLS_base_DxFem_`sample'.tex",
  					append /*booktabs
    cells(b(fmt(%9.3f)) se(par) p(par([ ])))
    prehead(
        `"\midrule"'
        `"\multicolumn{4}{l}{\textbf{Panel B: Men only}}\\ "'
    )
	posthead(`"\addlinespace"') 
					prefoot(`"\addlinespace   \hdashline \addlinespace"') 
					postfoot(`" "') 
    stats(
        N p_ri_D_male,
        fmt(%9.0f %9.3f)
        labels("N (Men)"
               "{Fisher p-val D (Men)}")
    ) 
	varlabels(D "Treatment", end(""), nolast)
	 keep(D) 
collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none)*/
;

*=============== Panel C: Women only ===============*
esttab OLS_base_F1 OLS_base_F2 OLS_base_F3 
	using "T8_Course_OLS_base_DxFem_`sample'.tex",
    		append /*booktabs
    cells(b(fmt(%9.3f)) se(par) p(par([ ])))
    prehead(
        `"\midrule"'
        `"\multicolumn{4}{l}{\textbf{Panel C: Women only}}\\ "'
    )
    stats(
        N p_ri_D_female,
        fmt(%9.0f %9.3f)
        labels("N (Women)"
               "{Fisher p-val D (Women)}")
    ) 
	posthead(`""')
    prefoot(
        `"\bottomrule"'
        `"\end{tabular}"'
    )
    postfoot(
        `"\begin{tablenotes}[flushleft]\footnotesize"'
        `"\item \textit{Notes}: Coefficients with clustered standard errors in parentheses ( ). Clustered \$p\$-values in brackets [ ]. Fisher randomization $p$-values in braces \{ \}."'
        `"\end{tablenotes}"'
        `"\end{threeparttable}"'
        `"\end{table}"'
    )
	varlabels(D "Treatment", end(""), nolast)
	    keep(D) 
collabels(, none) legend eqlabels(, none) nonumbers mlabels(, none)*/
;

#delimit cr

		

		}